package com.presto.directo.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.database.Cursor
import android.provider.ContactsContract
import androidx.core.app.ActivityCompat
import androidx.core.database.getLongOrNull
import com.presto.directo.entity.ContactAddressEntity
import com.presto.directo.entity.ValueEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object ContactUtil {

    suspend fun getContacts(context: Context): List<ContactAddressEntity> {
        return withContext(Dispatchers.IO) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                return@withContext listOf()
            }
            val contacts = mutableListOf<ContactAddressEntity>()
            var cursor: Cursor? = null
            return@withContext try {
                val resolver = context.contentResolver
                cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null)
                while (cursor!!.moveToNext()) {
                    // 取得联系人的名字索引
                    val nameIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)
                    val contactName = cursor.getString(nameIndex)
                    val updateTime = cursor.getLongOrNull(cursor.getColumnIndex(ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP))?.toString() ?: ""
                    // 取得联系人的ID索引值
                    val contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))
                    val phoneCur = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null) // 第一个参数是确定查询电话号，第三个参数是查询具体某个人的过滤值
                    val phoneList = mutableListOf<ValueEntity>()
                    try {
                        while (phoneCur!!.moveToNext()) {
                            val type = phoneCur.getInt(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))
                            val label: String = if (type == ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM) {
                                phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL)) ?: ""
                            } else {
                                (ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.resources, type, "") as String?) ?: ""
                            }
                            val strPhoneNumber = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) ?: ""
                            phoneList.add(ValueEntity(label, strPhoneNumber))
                        }
                    } catch (e: Exception) {
                    } finally {
                        phoneCur?.close()
                    }
                    val contactAddressBean = ContactAddressEntity(contactName, phoneList, updateTime)
                    contacts.add(contactAddressBean)
                }
                cursor.close()
                contacts
            } catch (e: Exception) {
                contacts
            } finally {
                cursor?.close()
            }
        }

    }

}

